package com.caiyi.financial.nirvana.sms.util;

import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.util.Map;
import java.util.SortedMap;
import java.util.TreeMap;

/**
 * Created by Mario on 2017/12/19 0019.
 * 签名校验工具类
 * 签名算法:
 * 请求参数按字母升序排列拼成queryString的形式：a=1&b=2&c=3...&z=26
 * 参数拼接完成后添加用户密码:a=1&b=2&c=3...&z=26&key={pwd}
 * 整个字符串计算MD5，获得sign
 */
public class SignUtil {

    private static final Logger logger = LoggerFactory.getLogger(SignUtil.class);

    private SignUtil() {
    }

    /**
     * 生成Sign
     *
     * @param params 参数
     * @param key    key
     * @return sign
     */
    public static String createSign(Map<String, String> params, String key) {
        SortedMap<String, String> sortedMap = new TreeMap<>(params);
        StringBuilder sortedParams = new StringBuilder();
        for (String item : sortedMap.keySet()) {
            if (StringUtils.isBlank(sortedMap.get(item)) || StringUtils.isBlank(item)) {
                logger.info("SignUtil createSign key is {} || values is {}", item, sortedMap.get(item));
                continue;
            }
            sortedParams.append(item).append("=").append(sortedMap.get(item)).append("&");
        }
        sortedParams.append("key=").append(key);
        return MD5Util.encode(sortedParams.toString());
    }

    /**
     * 校验Sign
     *
     * @param params 参数
     * @param key    用户密码
     * @param sign   待校验签名
     * @return 签名是否有效
     */
    public static boolean verifySign(Object params, String key, String sign) {
        try {
            Map mapParams = CommUtil.object2Map(params);
            if (mapParams.containsKey("sign")) {
                mapParams.remove("sign");
            }
            String curSign = createSign(mapParams, key);
            return curSign.equalsIgnoreCase(sign);
        } catch (Exception err) {
            return false;
        }
    }
}
